package com.demo.mqtt.common.utils;

import io.netty.buffer.ByteBuf;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 辅助工具类
 */
@Log4j2
public class AssistUtil {

    /**
     * 获取主机 IP 地址
     *
     * @return String IP
     * @throws UnknownHostException 找不到主机地址
     */
    public static String getHostAddress() {
        try {
            InetAddress address = InetAddress.getLocalHost();
            return address.getHostAddress();
        } catch (UnknownHostException unknownHostException) {
            log.error("找不到主机地址 => [{}]", unknownHostException.getMessage());
        }

        return null;
    }

    /**
     * 处理 ascii 的字节
     *
     * @param byteBuf 字节
     * @param length  长度
     * @return double
     */
    public static String processAsciiByte(ByteBuf byteBuf, int length) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < length; i++) {
            String hexStr = CodeUtil.byteToHexString(byteBuf.readByte());
            str.append(CodeUtil.hexStringToAsciiString(hexStr));
        }

        return str.toString();
    }

    /**
     * 处理科学计数法
     *
     * @param value   数值
     * @param byteBuf byteBuf
     * @return
     */
    public static double processScientificCount(Double value, ByteBuf byteBuf) {
        // 科学计数法格式 E(+/-)00

        // 跳过 "E"
        byteBuf.skipBytes(1);

        // 获取值
        StringBuilder num = new StringBuilder();
        for (int i = 0; i < 3; i++) {
            String asciiStr = CodeUtil.byteToHexString(byteBuf.readByte());
            num.append(CodeUtil.hexStringToAsciiString(asciiStr));
        }

        // 指数运算
        BigDecimal idx = BigDecimal.valueOf(Math.pow(10, Integer.parseInt(num.toString())));
        return new BigDecimal(value).multiply(idx).doubleValue();
    }

    /**
     * hexString => short
     *
     * @param str hexString
     * @return short
     */
    public static short hexString2Short(String str) {
        int val = hexString2Int(str);
        byte[] byteArray = new byte[2];

        // 具体跟字节序有关，可能需要调换位置
        byteArray[0] = (byte) (val & 0xFF);
        byteArray[1] = (byte) ((val >> 8) & 0xFF);

        return (short) (((byteArray[1] << 8) | byteArray[0] & 0xff));
    }

    /**
     * 16 进制 => 10进制
     *
     * @param str hexString
     * @return int
     */
    public static int hexString2Int(String str) {
        return Integer.parseInt(str, 16);
    }


    /**
     * isEmpty
     *
     * @param object
     * @return boolean
     */
    public static boolean isEmpty(Object object) {
        return StringUtils.isEmpty(object);
    }

    /**
     * 解析 String-Date 2 Date
     *
     * @param dateStr str
     * @param pattern 格式
     * @return java.util.Date
     */
    public static Date parseDateTime(String dateStr, String pattern) {
        if (AssistUtil.isEmpty(pattern)) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.parse(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Date();
    }

    /**
     * @return Date
     */
    public static Date getMongoDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.HOUR_OF_DAY, 8);
        return AssistUtil.parseDateTime(sdf.format(ca.getTime()), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     *
     * @param byteBuf
     * @param length
     * @return
     */
    public static String readByteBuf(ByteBuf byteBuf, int length) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < length; i++) {
            str.append( CodeUtil.byteToHexString(byteBuf.readByte()) );
        }

        return str.toString();
    }

}